<template>
    <div>
        <!-- 头部 -->
        <header class="w-34 py-5 w-full flex items-center justify-between">
            <aside class="w-[500px] flex items-center justify-between">
                <n-button type="primary" @click="getNewsList" class="mr-2">查询所有</n-button>
                <n-input 
                   v-model:value="keyword"
                    style="width: 300px;"
                     placeholder="关键字查询（回车即可）"
                     >
                     <template #prefix>
                        <n-icon :component="Search" />
                    </template>
                    </n-input>
                <div class="flex ml-2">
                    <n-select v-model:value="searchKey" :options="options" />
                    <n-button class="ml-2" type="warning" @click="SearchList">查询</n-button>
                </div>
            </aside>
            <aside class="w-1/2 justify-end flex items-center">
                <n-button @click="downloadAllCsv" type="success">
                    导出全部项目
                </n-button>
            </aside>
       
        </header>
        <!-- 表格 -->
        <n-data-table
            striped 
            ref="tableRef"
            :columns="columns"
            :data="NewList"
            :bordered="true"
            :pagination="paginationReactive"
        />
    </div>

    <n-drawer 
        v-model:show="editListVisable"
        placement="top"
        resizable
        height="100%"
        :z-index="19"
    >
      <n-drawer-content>
        <template #header>
            <header class="flex justify-between items-center">
                <n-space>
                    <n-button strong secondary :type="edit_type? 'tertiary': 'success'" @click="editChangType">编辑新闻</n-button>
                    <n-button strong secondary :type="edit_type? 'success': 'tertiary'" @click="editChangType">添加英文版</n-button>
                </n-space>
                <n-gradient-text type="error" @click="editListVisable = false">
                    退出编辑
                </n-gradient-text>
            </header>
        </template>
        <template #default>
            <main>
                <template v-if="!edit_type">
                    <edit v-model:cover="editviewContent.cover" v-model:title="editviewContent.zh_title" :news_id="editviewContent.news_id" v-model:value="editviewContent.zh_body" v-model:desc="editviewContent.zh_desc" ></edit>
                </template>
                <template v-else>
                    <edit v-model:cover="editviewContent.cover" v-model:title="editviewContent.zh_title" :news_id="editviewContent.news_id" v-model:value="editviewContent.zh_body" v-model:desc="editviewContent.zh_desc" :btn="false"></edit>
                </template>
            </main>
        </template>
      </n-drawer-content>
    </n-drawer>
</template>

<script setup lang="ts">
    import dayjs from 'dayjs'
    import Papa from 'papaparse';
    import { NButton, NIcon,NPopconfirm, NTag } from 'naive-ui';
    import { getCurrentInstance } from 'vue';
    import {Globe,Backspace,Search} from '@vicons/ionicons5'
    import { ref,onMounted,reactive } from 'vue'
    import { deleteProjectById } from '../../Api/list/index'
    let { proxy } = getCurrentInstance()
    let NewList = ref([]) // 列表
    let searchKey = ref('C')
    let options = reactive([
        {
          label: '公司报备',
          value: 'C'
        },
        {
          label: '个人报备',
          value: 'P'
        }
    ])
    // 生命周期
    onMounted(()=>{
        getNewsList()
    })
    /**
     * 数据渲染
     */
    let tableRef = ref()
    const columns = [
        {
            title: '项目编号',
            key: 'project_ref',
            width: '20%',
            align: 'center',
        },
        { 
            title: '报备人', 
            key: 'username',
            width: '100px',
            align: 'center'

         },
        { title: '报备人手机号码', key: 'phone', width: '10%', align: 'center' },
        { 
            title: '项目负责人', 
            key: 'admin', 
            align: 'center', 
            width: '10%',
            render: (row: Record<string,any>) => {
                return h('div',{style: {color: '#e74c3c',fontWeight: 'bold'}},row.admin)
            }
        },
        {
            title: '项目名称',
            key: 'project_name',
            width: '20%',
            align: 'center',
            ellipsis: {
                tooltip: true
            },
            render: (row) => {
                return h('div',{style: {'color': '#f0a020','font-weight': 'bold'}},row.project_name)
            }
        },
        {
            title: '提交时间',
            key: 'createdAt',
            width: '10%',
            render: (row) => {
                return h('div', {}, dayjs(row.createdAt).format('YYYY-MM-DD HH:mm:ss'))
            },
            defaultSortOrder: 'descend',
            sorter: 'default',
        },
        {
            title: '项目状态',
            key: 'status',
            width: '100px',
            align: 'center',
            render(row:any) {
                let tag = row.status as number
                switch(tag) {
                    case 0:
                        return h(NTag, { type: 'info' }, () => '待审核')
                    case 1:
                        return h(NTag, { type: 'success' }, () => '已通过')
                    case 2:
                        return h(NTag, { type: 'error' }, () => '被驳回')
                }
            }
        },
        { title: '操作', key: 'action', width: '140px', align: 'center',render(row) {
            return h('div', 
            {
                style: { display: 'flex', justifyContent: 'center' }
            },
            [
                h(NPopconfirm,{
                    onPositiveClick: async () => {
                        let id:number = row.project_id // 用户留言编号
                        handlePositiveClick(id)
                    },
                    onNegativeClick: () => {
                        proxy.$message.info("取消删除")
                    }
                },{
              trigger: () => h(NButton,{ type: 'error',size: 'small'},[
                h(NIcon,{size:16,component: Backspace,color: '#fff'}),
                h('span',{style: {marginLeft: '5px'}},'删除')
            ]),
              default: () => h(
              'div', 
              '确定删除吗？',
            )
            })
            ])
        }}
    ]
    let keyword = ref('')
    enum pro_type {
        C = '公司项目', // 公司报备
        P = '个人项目'
    }
    const SearchList = async() => {
        let res = await proxy.$http.get("/weixin/getProjectByType/" + searchKey.value)
        if (res.data.code !== 200) return proxy.$message.error('获取失败')
        NewList.value = res.data.data
        proxy.$message.success(`获取${pro_type[searchKey.value]}`)
    }
    // 获取列表
    const getNewsList = async () => {
        let res = await proxy.$http.get("/weixin/getAllProject")
        NewList.value = res.data.data
    }

  

    // 确认删除
    const handlePositiveClick = async (id: number) => {
       let res = await deleteProjectById(id)
        if(res.code === 200){
            proxy.$message.success("删除成功")
            getNewsList()
        } else {
            proxy.$message.error("删除失败")
        }
    }


    /**
     * 分页操作
     */
     const paginationReactive = reactive({
      page: 1,
      pageSize: 5,
      showSizePicker: true,
      pageSizes: [5, 10, 15],
      onChange: (page: number) => {
        paginationReactive.page = page
      },
      onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
      }
    })
    const pageCount = ref(3)
    const page = ref(1)
    const pageSize = ref(3)
    const pageSizes = [
        {
            label: "5 每页",
            value: 10
        },
        {
            label: "10 每页",
            value: 15
        }
    ]
    import {FlashOutline} from '@vicons/ionicons5'
    import { h } from 'vue';
 
    /**
     * 项目导出
     */
    // 1. 导出所有项目
    const fieldAliases = ref<Record<string, string>>({
      project_ref: '项目编号',
      start_time: '预计招标日期',
      end_time: '项目结束时间',
      username: '报备人',
      phone: '报备人手机号',
      admin: '项目负责人',
      project_name: '项目名称',
      company_name: '公司名称',
      money: '项目金额',
      project_num: '设备数量（台）',
      status: '项目状态',
      createdAt: '项目发布时间',
      updatedAt: '项目修改时间'
    });
     const downloadAllCsv = () => {
        try {
            let data = NewList.value.map((item: Record<string,string | number>) => {
            let obj: Record<string,string | number> = {}
            for(let key in fieldAliases.value) {
                if (key == 'createdAt' || key == 'updatedAt' || key == 'start_time' || key == 'end_time') {
                    obj[fieldAliases.value[key]] = item[key]? dayjs(item[key]).format('YYYY-MM-DD HH:mm:ss'): ''
                } else if (key == 'status') {
                    obj[fieldAliases.value[key]] = item[key] === 0 ? "待审批" : (item[key] == 1? '已通过': '被驳回')
                } else {
                    obj[fieldAliases.value[key]] = item[key]
                }
            }
            return obj
        })
          let csv = Papa.unparse(data)
          const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
          const link = document.createElement('a');
          const url = URL.createObjectURL(blob);
          link.setAttribute('href', url);
          link.setAttribute('download', 'data.csv'); // 设置下载文件名

          // 将 <a> 元素添加到 DOM 中并触发点击事件
          document.body.appendChild(link);
          link.click();

          // 清理临时创建的对象
          document.body.removeChild(link);
          URL.revokeObjectURL(url);

        } catch(err) {
            proxy.$message.error("导出失败")
        }
     }

</script>

<style lang="less" scoped>
    :deep(.n-data-table__pagination) {
        display: flex;
        justify-content: center;
    }
    :deep(.n-drawer-header__main) {
        width: 100%!important;
    }
    :deep(.MsoNormal) {
        display: flex;
        justify-content: center;
    }
    :deep(.n-pagination) {
        display: flex;
        justify-content: center;
    }
</style>